package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.annotation.Incomplete;
import org.aeon.message.request.GroupQuitRequestMessage;
import org.aeon.message.response.GroupQuitResponseMessage;
import org.aeon.service.ChatGroupService;
import org.aeon.service.UserGroupRelationService;
import org.aeon.service.factory.ChatGroupServiceFactory;
import org.aeon.service.factory.UserGroupRelationServiceFactory;

/**
 * @author: MissingAeon
 * @date: 2024/2/19 8:54
 * @description: 组退出请求处理程序
 */
@Slf4j
@ChannelHandler.Sharable
@Incomplete
public class GroupQuitRequestHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        final GroupQuitResponseMessage resMsg = new GroupQuitResponseMessage();
        final Long groupId = msg.getGroupId();

        final ChatGroupService groupService = ChatGroupServiceFactory.getService();
        // 判断群聊是否存在
        if (groupService.isChatGroupExist(groupId)) {
            final UserGroupRelationService groupRelationService = UserGroupRelationServiceFactory.getService();
            final Long userId = msg.getUserId();
            // 查询是否为该群群主
            if (groupService.isCreator(groupId, userId)) {
                // 群主退出则为解散群聊
                final int i = groupService.deleteGroup(groupId);
                if (i == 1) resMsg.setResponse(true, "已解散该群聊");
                else resMsg.setResponse(false, "解散该群聊失败");
            }
            // 判断查询用户是否为群聊成员
            else if (groupRelationService.isGroupMember(groupId, userId)) {
                final int i = groupRelationService.deleteUserGroupRelation(groupId, userId);
                if (i == 1) resMsg.setResponse(true, "已退出该群聊");
                else resMsg.setResponse(false, "退出该群聊失败");
            } else {
                resMsg.setResponse(false, "未是该群聊成员");
            }
        } else {
            resMsg.setResponse(false, "该群聊不存在");
        }
        ctx.writeAndFlush(resMsg);
    }
}
